package conf

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2020-06-12
Description: 数据库配置文件
*******************************************************************************/
import (
	"encoding/json"
	"io/ioutil"
	"sync"

	"gitee.com/cloudapex/ulern/cto"
	"gitee.com/cloudapex/ulern/rds"
	"gitee.com/cloudapex/ulern/util"
)

type DBSetting struct {
	DBHost string `json:"dbHost"`
	DBPort uint32 `json:"dbPort"`
	DBName string `json:"dbName"`
	DBUser string `json:"dbUser"`
	DBPass string `json:"dbPass"`
}

//------------------------------------------------------------------------------
//======================================DB======================================
//------------------------------------------------------------------------------
var DB *dbConf

func init() { DB = cto.Preload("MT_DB", &dbConf{}).(*dbConf) }

type dbConf struct {
	mutx sync.Mutex
	main *mainDB
}
type mainDB struct {
	ShowSQL bool `json:"showSql"`

	MDBs []DBSetting  `json:"mdbs"`
	RDBs []rds.Config `json:"rdbs"`
}

func (this *dbConf) HandleInit() error {
	this.main = &mainDB{}
	data, err := ioutil.ReadFile(this.HandlePath())
	if err != nil {
		return err
	}
	return json.Unmarshal(data, this.main)
}
func (this *dbConf) HandlePath() string { return util.ExePathJoin("confs/db.json") }

func (this *dbConf) HandleContent() string {
	b, err := json.MarshalIndent(this.main, "", "\t")
	if err != nil {
		return err.Error()
	}
	return string(b)
}
func (this *dbConf) HandleReload() error {
	data, err := ioutil.ReadFile(this.HandlePath())
	if err != nil {
		return err
	}

	temp := &mainDB{}
	if err := json.Unmarshal(data, temp); err != nil {
		return err
	}
	defer util.UnLock(util.Lock(&this.mutx))
	// update some fields
	return cto.ErrSettingNotNeed
}

//------------------------------------------------------------------------------
//================================开放方法=======================================
//------------------------------------------------------------------------------
func (this *dbConf) Stg() *mainDB {
	defer util.UnLock(util.Lock(&this.mutx))
	return this.main
}

func (this *dbConf) ShowSQL() bool { return this.Stg().ShowSQL }

func (this *dbConf) MDBs() []DBSetting  { return this.Stg().MDBs }
func (this *dbConf) RDBs() []rds.Config { return this.Stg().RDBs }
